<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2018/1/12
 * Time: 11:33
 */

namespace app\teacher\controller;


use app\common\model\app\ConstLinkType;
use app\common\model\DynamicFlow;
use app\common\model\Topic as TopicModel;
use app\common\model\TopicChat;
use app\common\model\TopicEssay;
use app\common\model\UserNoticeMessage;
use app\common\utils\DateTimeUtil;
use app\teacher\lib\ApiResponse;
use app\teacher\lib\TeacherBaseController;
use library\JPushZDY;
use think\Db;
use think\Request;

class Topic extends TeacherBaseController
{
    /**
     * 话题
     *
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request) {
        if ($request->isGet()) {
            return $this->topic_get();
        } elseif ($request->isPost()) {
            return $this->topic_save();
        }elseif ($request->isDelete()) {
            return $this->topic_del();
        } else {
            return json(null,405);
        }
    }
    private function topic_get() {
        $form = $this->validFormData([
            ['id', 'integer',],
        ]);

        if (isset($form['id'])) {
            $topic = TopicModel::get($form['id']);
            if ($topic->teacher_id != $this->teacherId) {
                return ApiResponse::error(ApiResponse::ERR_FORBIDDEN_SOURCE,'不属于你的话题');
            }
            $topic->is_current = date('Y-m-d') == $topic->play_date;
            return ApiResponse::success($topic);
        } else {
            $page = TopicModel::manageList($this->teacherId, $this->rows, $this->page,$form['keywords']??null);
            $result = $page->toArray();

            $result['code'] = 200;
            return $result;
        }
    }
    private function topic_save() {
        $rules = [
            ['title', 'require',],
        ];
        $form = $this->validFormData($rules);

        Db::transaction(function () use ($form) {
            $isNew = false;
            $today = date('Y-m-d');
            $topic = TopicModel::get(['teacher_id'=>$this->teacherId,'play_date'=>$today]);
            if (empty($topic)) {
                $topic = new TopicModel();
                $topic->teacher_id = $this->teacherId;
                $topic->play_date = $today;
                $isNew = true;
            }
            $topic->title = $form['title'];
            $topic->save();

            if ($isNew) {
                $topic->makeDynamicData($isNew, DynamicFlow::SOURCE_TEACHER);

                // 创建直播话题推送消息
                $msg = "掌乾财经名师图文直播开始啦！{$form['title']}";
                $extras = UserNoticeMessage::makeExtras(ConstLinkType::LINK_TYPE_TOPIC, $topic->id);
                $res = JPushZDY::pushAll($msg, $extras);
            }
        });

        return ApiResponse::success();
    }
    private function topic_del() {
        $form = $this->validFormData([
            ['id', 'require|integer',],
        ]);

        TopicModel::del($form['id']);

        return ApiResponse::success();
    }

    /**
     * 图文直播
     *
     * @param Request $request
     * @return mixed
     */
    public function essay(Request $request) {
        if ($request->isGet()) {
            return $this->essay_list();
        } elseif ($request->isPost()) {
            return $this->essay_save();
        } elseif ($request->isDelete()) {
            return $this->essay_del();
        } else {
            return json(null,405);
        }
    }
    private function essay_list() {
        $form = $this->validFormData([
            ['topic_id', 'require|integer',],
        ]);
        if (!TopicModel::checkOwn($form['topic_id'], $this->teacherId)) {
            return ApiResponse::error(ApiResponse::ERR_FORBIDDEN_SOURCE);
        }

        $query = Db::table('topic_essay e');
        $query->where('e.topic_id','=', $form['topic_id']);
        $query->order('e.id','desc');
        $page = $query->paginate($this->limit,false,['page'=>$this->page]);
        $result = $page->toArray();
        foreach ($result['data'] as & $item) {
            $item['created'] = DateTimeUtil::format($item['created']);
        }

        $result['code'] = 200;
        return $result;
    }
    private function essay_save() {
        $form = $this->validFormData([
            ['topic_id','require|integer',],
//            ['title','require',],
            ['content','require',],
        ]);
        if (!TopicModel::checkOwn($form['topic_id'], $this->teacherId)) {
            return ApiResponse::error(ApiResponse::ERR_FORBIDDEN_SOURCE);
        }

        if (!empty($form['id'])) {
            TopicEssay::update($form,[], TopicEssay::getSaveFields());
        } else {
            TopicEssay::create($form, TopicEssay::getSaveFields());
        }

        return ApiResponse::success();
    }
    private function essay_del() {
        $form = $this->validFormData([['id','require|integer']]);
        if (!TopicModel::checkOwn($form['id'], $this->teacherId)) {
            return ApiResponse::error(ApiResponse::ERR_FORBIDDEN_SOURCE);
        }

        TopicEssay::destroy($form['id']);
        return ApiResponse::success();
    }

    /**
     * 直播话题互动
     *
     * @param Request $request
     * @return mixed
     */
    public function chat(Request $request) {
        if ($request->isGet()) {
            return $this->chat_list();
        } elseif ($request->post()) {
            if ($request->param('reply_id')) {
                return $this->chat_reply();
            } else {
                return $this->chat_create();
            }
        } else {
            return json(null,405);
        }
    }
    private function chat_list() {
        $form = $this->validFormData([
            ['topic_id', 'require|integer',],
        ]);

        if (0 == $form['topic_id']) {
            return ApiResponse::success();
        }
        if (!TopicModel::checkOwn($form['topic_id'], $this->teacherId)) {
            return ApiResponse::error(ApiResponse::ERR_FORBIDDEN_SOURCE);
        }

        $result = TopicChat::list($form['topic_id'],$this->limit,$this->page,true);

        $result['code'] = 200;
        return $result;
    }
    private function chat_create() {
        $form = $this->validFormData([
            ['content', 'require',],
            ['topic_id', 'require|integer',],
        ]);
        if (!TopicModel::checkOwn($form['topic_id'], $this->teacherId)) {
            return ApiResponse::error(ApiResponse::ERR_FORBIDDEN_SOURCE);
        }

        $data = [
            'content' => $form['content'],
            'topic_id' => $form['topic_id'],
        ];
        if (isset($form['id'])) {
            $data['id'] = $form['id'];
            TopicChat::update($data);
        } else {
            TopicChat::create($data);
        }

        return ApiResponse::success();
    }
    private function chat_reply() {
        $form = $this->validFormData([
            ['reply_id','require|integer',],
            ['content','require',],
        ]);

        $re_chat = TopicChat::get($form['reply_id']);
        if (empty($re_chat)) ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,'回复目标不存在');
        if (!TopicModel::checkOwn($re_chat->topic_id, $this->teacherId)) {
            return ApiResponse::error(ApiResponse::ERR_FORBIDDEN_SOURCE);
        }

        $data = [
            'content' => $form['content'],
            'reply_target_id' => $re_chat->id,
            'topic_id' => $re_chat->topic_id,
        ];
        TopicChat::create($data);

        return ApiResponse::success();
    }

}